import {
  Component,
  Input,
  OnInit,
  ChangeDetectionStrategy,
  Output,
  EventEmitter,
  ChangeDetectorRef,
} from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';

export interface Footer {
  icon: string;
  iconActive: string;
  title: string;
  link: string;
}
@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FooterComponent implements OnInit {
  @Input() footerData!: Footer[];
  @Output() tabSelected = new EventEmitter();
  currentIndex: number = 0;
  constructor(private router: Router, private changeRef: ChangeDetectorRef) {}
  ngOnInit() {
    this.urlInFooterDataIndex((url: string) => {
      const urlStr = url.split('/')[1];
      switch (urlStr) {
        case 'home':
          this.currentIndex = 0;
          break;
        case 'cart':
          this.currentIndex = 1;
          break;
        case 'category':
          this.currentIndex = 2;
          break;
        case 'chart':
          this.currentIndex = 3;
          break;
        case 'my':
          this.currentIndex = 4;
          break;
        default:
          break;
      }
      this.changeRef.markForCheck();
    });
  }
  handleClick(index: number): void {
    this.currentIndex = index;
    this.tabSelected.emit(this.footerData[index]);
  }
  urlInFooterDataIndex(callback: any) {
    const endNav = this.router.events.pipe(
      filter((item) => item instanceof NavigationEnd)
    ) as Observable<NavigationEnd>;
    const sub = endNav.subscribe(
      (result: NavigationEnd) => {
        callback(result.url);
      },
      (error) => {
        console.log(error);
      },
      () => {
        sub.unsubscribe();
      }
    );
  }
}
